package com.oocl.homework0711.action;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import com.oocl.homework0711.customer.Customer;
import com.oocl.homework0711.parse.Parse;
import com.oocl.homework0711.printformat.imp.DatePrintImp;
import com.oocl.homework0711.scanner.imp.DateScannerImp;
import com.oocl.homework0711.sort.imp.SortCustomers;

public class NetworkAction {
	public void tcp() throws IOException {
		DateScannerImp dateScannerImp = new DateScannerImp(new FileInputStream("data.txt"));
		List<Customer> listCustomers = dateScannerImp.scann();
		
		ServerSocket server = new ServerSocket(8888);
		Socket socket = server.accept();
		OutputStream out = socket.getOutputStream();
		//BufferedOutputStream out2 = new BufferedOutputStream(socket.getOutputStream());
		InputStream in = socket.getInputStream();
		out.write("Please input the action you want,the format as \"L  id   xml \",and Q is exit!!\n\r ".getBytes());
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String command = reader.readLine();
		while(command!=null){
			try {
				String[] strings = new Parse().parseCommand(command);
				if(strings==null){
					//OutputStream out3 = socket.getOutputStream();
					out.write(("Input Error !!Please input again !!\n\r").getBytes());
					//break;
					in = socket.getInputStream();
					reader = new BufferedReader(new InputStreamReader(in));
					command = reader.readLine();
					
					//reader = new BufferedReader(new InputStreamReader(in));
				}else if (strings[0].equals("quit")) {
					out.write("quit !!! ".getBytes());
					out.close();
					in.close();
					socket.close();
					server.close();
					return;
				}else {
					SortCustomers sortCustomers = new SortCustomers();
					TreeSet<Customer> treeSetCustomers= sortCustomers.sortCustomers(listCustomers, strings[0]);
					StringBuilder stringBuilder = new DatePrintImp().printFormat(treeSetCustomers, strings[1]);
					for(byte c:stringBuilder.toString().getBytes()){
						out.write(c);
						reader = new BufferedReader(new InputStreamReader(in));
					}
					out.write("Please input the action you want,the format as \"L  id   xml \",and Q is exit!! \n\r".getBytes());
					in = socket.getInputStream();
					reader = new BufferedReader(new InputStreamReader(in));
					command = reader.readLine();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				out.write("ERROR !!! \n".getBytes());
			}
		}
		out.close();
		in.close();
		socket.close();
		server.close();
		return;
	}
}
